<template>
  <div class="workflow-canvas">
    <div ref="canvasRef" id="js-canvas"></div>
  </div>
</template>

<script>
import BpmnViewer from 'bpmn-js/lib/Viewer'
import ZoomScrollModule from "diagram-js/lib/navigation/zoomscroll";
import MoveCanvasModule from "diagram-js/lib/navigation/movecanvas";
import 'diagram-js/lib/model'
export default {
  name: "WorkflowBpmnViewer",
  props: {
    bpmnXml: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      bpmnViewer: null
    }
  },
  methods: {
    load(xml) {

      if (!xml) {
        return
      }
      if (!this.bpmnViewer) {
        this.bpmnViewer = new BpmnViewer({
          container: this.$refs.canvasRef,
          additionalModules: [
            ZoomScrollModule,MoveCanvasModule
          ],
          height: 500,
        });
      }

      this.bpmnViewer.importXML(xml).then(({warnings}) => {
        this.bpmnViewer.get('canvas').zoom('fit-viewport',"auto");
        this.setColor()
      });
    },setColor() {
      // access viewer components
      const canvas = this.bpmnViewer.get("canvas");

      // 获取到全部节点
      const allShapes = this.bpmnViewer.get("elementRegistry").getAll();

      //循环节点添加颜色
      allShapes.forEach(element => {
        const shapeId = element.businessObject.id;
        const shapeAttrs = element.businessObject.$attrs;

        // add marker
        if (element.businessObject.$type != "bpmn:Group") {
          if (element.businessObject.$type == "bpmn:SequenceFlow") {
            canvas.addMarker(shapeId, "highlight-2" + shapeAttrs.run_state);
          } else {
            canvas.addMarker(shapeId, "highlight-" + shapeAttrs.run_state);
          }
        }
      });
    }, destroy() {
      if (this.bpmnViewer) {
        this.bpmnViewer.destroy();
        this.bpmnViewer = null
      }
    }
  },
  watch: {
    bpmnXml(val) {
      this.load(val)
    }
  },
  mounted() {
    this.load(this.bpmnXml)
  }, beforeUnmount() {
    this.destroy()
  }
}
</script>

<style lang="less" scoped>
.workflow-canvas {
  width: 100%;
  height: 500px;
  position: relative;

  :deep(.bjs-powered-by) {
    display: none;
  }
}
</style>
<style>
.highlight-0 .djs-visual > :nth-child(1) {
  stroke: black !important;
}
.highlight-1 .djs-visual > :nth-child(1) {
  stroke: black !important;
  fill: #f8f8f8 !important;
}
.highlight-2 .djs-visual > :nth-child(1) {
  stroke: black !important;
  fill: #cff5fa !important;
}
.highlight-3 .djs-visual > :nth-child(1) {
  stroke: black !important;
  fill: #d7f6ce !important;
}

/* 连线 */
.highlight-20 .djs-visual > :nth-child(1) {
  stroke: black !important;
}
.highlight-23 .djs-visual > :nth-child(1) {
  stroke: green !important;
}
.highlight-24 .djs-visual > :nth-child(1) {
  stroke: red !important;
}
</style>
